/**
 * Created by ��־�� on 2017/2/20.
 */
import React from 'react';
import crypto from "crypto";
import {Comment} from "../comment";
import {IfDispatcher} from "../store/dispatcher";
import Underscore from "underscore";

export var Staff = React.createClass({
    contextTypes: {
        router: React.PropTypes.object.isRequired,
    },
    getInitialState(){
        return{
            password1:"",
            password2:"",
            userindex:null,
            ifpassequal:true,
            ifpassenull:false,
            ifduplicate:false,
            inputoldpassword:"",
            newpassIfEqualOldpass:false,
            newpassIfMatchKinds:true,
            newpassIfMatchLength:true,
            newpassIfEqualUsername:false,
            inputOldpassIfEqualOriginalPass:true,
            ifexistId:false,
            ifFourSame:false,
            ifTimeBt:false,
            timeinterval:false,
            oldnewKinds:false,
        }
    },
    componentDidMount(){
        var loginInfo = this.props.loginInfo;
        if(!loginInfo.name){
            this.context.router.push("/fronpage");
            IfDispatcher.dispatch({
                actionType:Comment.LOGOUT
            });
        }
    },
    handleChange(name,event){
        var newstate = {};
        newstate[name] = event.target.value;
        newstate.iferror = false;
        newstate.ifduplicate = false;
        newstate.ifpassequal = true;
        newstate.ifpassenull = false;
        newstate.newpassIfMatchKinds = true;
        newstate.newpassIfMatchLength = true;
        newstate.newpassIfEqualUsername = false;
        newstate.inputOldpassIfEqualOriginalPass = true;
        newstate.newpassIfEqualOldpass = false;
        newstate.ifexistId=false;
        newstate.ifFourSame=false;
        newstate.ifTimeBt=false;
        newstate.timeinterval=false;
        newstate.oldnewKinds = false;
        this.setState(newstate);
    },
    confirmReset(){
        var loginInfo = this.props.loginInfo;
        //var loginuser = this.props.loginInfo.name;
       // var loginoldpass = this.props.loginInfo.pass;
        if(this.state.password1 && this.state.password2 && this.state.inputoldpassword) {
            if (this.state.password1 != this.state.password2) {
                this.setState({ifpassequal:false})
            }else if(this.state.inputoldpassword==this.state.password1){
                this.setState({newpassIfEqualOldpass:true})
            }
            else if(this.validatePassword(this.state.password1)==1 || this.validatePassword(this.state.inputoldpassword)==1){
                this.setState({newpassIfMatchKinds:false})
            }else if(this.state.password1.length<6 || this.state.password1.length>20){
                this.setState({newpassIfMatchLength:false})
            }
            else if(this.state.inputoldpassword.length<6 || this.state.inputoldpassword.length>20){
                this.setState({newpassIfMatchLength:false})
            }
            else if(this.checkpassClick(this.state.inputoldpassword,this.state.password1) < 2){
                this.setState({oldnewKinds:true});
            }
            //else if(loginuser==this.state.password1){
            //    this.setState({newpassIfEqualUsername:true})
            //}
            //else if(loginoldpass!=inputOldPassMd5){
            //    this.setState({inputO
            // ldpassIfEqualOriginalPass:false})
            //}
            else {
                var that = this;
                $("#ajaxloading").show();
                $.ajax({
                    url: Comment.DATA_URL+"KDB/GetSalt",
                    data: $.param({
                        username:loginInfo.name
                    }),
                    type: 'GET',
                    contentType: 'application/x-www-form-urlencoded',
                    success: function (data) {
                        var msg = data;
                        var salt = msg.data;
                        var inputOldPassMd5="";
                        if(that.state.inputoldpassword){
                            //var hash = crypto.createHash("md5");
                            //hash.update(this.state.inputoldpassword);
                            //inputOldPassMd5=hash.digest("hex");
                            var keys = crypto.pbkdf2Sync(that.state.inputoldpassword, salt, 10000, 16, 'sha512');
                            inputOldPassMd5=keys.toString('hex');
                        }
                        var key = crypto.pbkdf2Sync(that.state.password1,salt, 10000, 16, 'sha512');
                        $.ajax({
                            url:Comment.DATA_URL+"KDB/EditUser",
                            data: $.param({
                                userId:loginInfo.userid,
                                optId:loginInfo.userid,
                                state:1,
                                //password:hash.digest("hex"),
                                password:key.toString('hex'),
                                oldPassword:inputOldPassMd5,
                            }),
                            type:'POST',
                            contentType: 'application/x-www-form-urlencoded',
                            success:function(data){
                                $("#ajaxloading").hide();
                                that.logoutClick();
                            },
                            error:function () {
                                $("#ajaxloading").hide();
                            },
                            statusCode:{
                                406:function (){
                                    IfDispatcher.dispatch({
                                        actionType:Comment.LOGOUT
                                    });
                                },
                                414:function(){
                                    that.setState({
                                        ifexistId:true,
                                    })
                                },
                                415:function(){
                                    that.setState({
                                        ifTimeBt:true,
                                    })
                                },
                                413:function(){
                                    that.setState({
                                        ifFourSame:true,
                                    })
                                },
                                422:function(){
                                    that.setState({inputOldpassIfEqualOriginalPass:false});
                                },
                                416:function(){
                                    that.setState({newpassIfEqualUsername:true});
                                },
                                429:function(){
                                    that.setState({timeinterval:true});
                                }
                            }
                        });
                    },
                    error:function(){
                        $("#ajaxloading").hide();
                    },
                    statusCode:{
                        424:function(){
                             alert("It doesn't match the salt value.");
                        },
                    }
                });
                //var hash = crypto.createHash("md5");
                //hash.update(this.state.password1);
            }
        }else{
            this.setState({ifpassenull:true})
        }
    },
    logoutClick(){
        IfDispatcher.dispatch({
            actionType:Comment.LOGOUT
        });
    },
    cancleToReset(){
        this.context.router.push("/project");
    },
    CharMode(iN) {
        if (iN >= 48 && iN <= 57)//数字
            return 1;
        if (iN >= 65 && iN <= 90) //大写字母
            return 2;
        if ((iN >= 97 && iN <= 122) || (iN >= 65 && iN <= 90)) //大小写
            return 4;
        else  return 8; //特殊字符
    },
    bitTotal(num) {
        var modes = 0;
        for (var i = 0; i < 4; i++) {
            if (num & 1) modes++;  num >>>= 1;
        }
        return modes;
    },

    validatePassword(password){
        var Modes = 0;
        for (var i = 0; i < password.length; i++) {
            Modes |= this.CharMode(password.charCodeAt(i));
        }
        return this.bitTotal(Modes); //CharMode函数
    },
   checkpassClick(oldpass,newpass){
       var ifnum = 0;
       if(Math.abs(newpass.length - oldpass.length) >= 2){
           ifnum = 2;
       }else{
           for(var index=0;index <newpass.length;index++){
               if(ifnum <2 && (oldpass.indexOf(newpass.charAt(index)) < 0)){
                    ifnum++;
               }
           }
       }
       return ifnum;
   },
    render(){
        var loginInfo = this.props.loginInfo;
        var staffdisable = "";
        if(loginInfo.iftamr){
            staffdisable = "disabled";
        }
        var pageHeight = this.props.propsheight;
        var disStyle = this.state.ifpassequal?{display:"none"}:{};
        var passnullSty = this.state.ifpassenull?{}:{display:"none"};
        var newpassIfMatchLengthSty = this.state.newpassIfMatchLength?{display:"none"}:{};
        var newpassIfMatchKindsty = this.state.newpassIfMatchKinds?{display:"none"}:{};
        var newpassIfEqualUsernameSty = this.state.newpassIfEqualUsername?{}:{display:"none"};
        var newIfEqualOldStyle = this.state.newpassIfEqualOldpass?{}:{display:"none"};
        var inputOldpassIfEqualOriginalPassSty = this.state.inputOldpassIfEqualOriginalPass?{display:"none"}:{};
        var ifExistIdStyle = this.state.ifexistId?{}:{display:"none"};
        var ifFourSameStyle= this.state.ifFourSame?{}:{display:"none"};
        var ifTimeBtStyle= this.state.ifTimeBt?{}:{display:"none"};
        var iftimeinterval = this.state.timeinterval?{}:{display:"none"};
        var ifoldnewKinds = this.state.oldnewKinds?{}:{display:"none"};
        return(
            <div>
                <div className="row" style={{height:"50px",backgroundColor:"#FFFFFF",marginLeft:"0px",marginRight:"0px"}}>
                    <div className="col-sm-12 " >
                        <span style={{color:"#9D9D9D"}}><h4>Account Management</h4></span>
                    </div>
                </div>
                <div className="row" style={{height:"10px",backgroundColor:"#408080",marginLeft:"0px",marginRight:"0px"}}>
                </div>

                <div className="row" style={{height:(pageHeight-130+"px"),backgroundColor:"#FFFCEC",marginLeft:"0px",marginRight:"0px"}}>
                    <div className="col-sm-8 col-sm-offset-2">
                        <div className="panel panel-default" style={{marginTop:"50px"}}>
                            <div className="panel-heading">
                                <span>Reset Password</span>
                            </div>
                            <div className="panel-body">
                                <div className="row">
                                    <div className="col-sm-10 col-sm-offset-1">
                                        <form>
                                            <div className="form-group">
                                                <label htmlFor="personnewpass2nd">Old Password</label>
                                                <input type="password" className="form-control" id="inputoldpassword" placeholder="Old Password"
                                                       onChange={this.handleChange.bind(this,"inputoldpassword")} value={this.state.inputoldpassword}
                                                />
                                                <label htmlFor="personnewpass">New Password</label>
                                                <input type="password" className="form-control" id="personnewpass" placeholder="New Password"
                                                       onChange={this.handleChange.bind(this,"password1")} value={this.state.password1}
                                                />
                                                <label htmlFor="personnewpass2nd">Retype New Password</label>
                                                <input type="password" className="form-control" id="personnewpass2nd" placeholder="New Password Again"
                                                       onChange={this.handleChange.bind(this,"password2")} value={this.state.password2}
                                                />
                                            </div>

                                        </form>
                                    </div>
                                </div>

                            </div>
                            <div className="panel-footer">
                                <div className="row">
                                    <div className="col-sm-3 col-sm-offset-1">
                                        <button
                                            role="button"
                                            className="btn btn-default"
                                            onClick={this.confirmReset}
                                            disabled={staffdisable}
                                        >Confirm</button>
                                    </div>
                                    <div className="col-md-7">
                                        <div style={disStyle}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                The new passwords do not match. Please retype the new passwords.
                                            </div>
                                        </div>
                                        <div style={ifoldnewKinds}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                There are two or more differences between the two characters and the length of the password.
                                            </div>
                                        </div>
                                        <div style={iftimeinterval}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                The interval cannot be less than the minimum period.
                                            </div>
                                        </div>
                                        <div style={passnullSty}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                All passwords can't be empty.
                                            </div>
                                        </div>
                                        <div style={ifExistIdStyle}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                This id does not exist!
                                            </div>
                                        </div>
                                        <div style={ifFourSameStyle}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                New password cannot be the same as the previous four password.
                                            </div>
                                        </div>
                                        <div style={ifTimeBtStyle}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                Password change interval for 5 minutes, not frequent revision.
                                            </div>
                                        </div>

                                        <div style={newIfEqualOldStyle}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                New password is equal original password.
                                            </div>
                                        </div>

                                        <div style={newpassIfMatchKindsty}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                Your new passwords must be at least  two kinds of characters.
                                            </div>
                                        </div>
                                        <div style={newpassIfMatchLengthSty}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                Your new passwords must be at least  six characters and at most 20 characters.
                                            </div>
                                        </div>

                                        <div style={newpassIfEqualUsernameSty}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                The password cannot be the same as an account or a reverse account.
                                            </div>
                                        </div>
                                        <div style={inputOldpassIfEqualOriginalPassSty}>
                                            <div className="alert alert-danger col-md-12" role="alert" style={{marginBottom:"-5px",marginTop:"-10px"}} >
                                                Old password is not equal your original password.
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>

                </div>
            </div>
        )
    }
});